//
//  WIFIManagerViewController.m
//  Router
//
//  Created by teki on 15/10/13.
//  Copyright © 2015年 dc. All rights reserved.
//

#import "WIFIManagerViewController.h"
#import "WIFIManagerTableViewCell.h"
#import "WIFIManagerHeaderView.h"
#import "SettingSSIDAndPasswordViewController.h"

#import "MyViewController.h"
#import "WIFIDeviceSettingViewController.h"
#import "LoginResponseModel.h"
#import "RateModel.h"
#import "WIFIHelper.h"
#import "UserHelper.h"

#import "DiscoverNewWIFIController.h"


@interface WIFIManagerViewController ()
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) WIFIManagerHeaderView *headerView;
@property (nonatomic, strong) WIFIHelper *wifiHelper;
@property (nonatomic, strong) UserHelper *userHelper;
@end

@implementation WIFIManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.wifiHelper =[[WIFIHelper alloc] init];
    self.userHelper = [[UserHelper alloc] init];
    [self addRightBarButtonWithNormalImageName:@"home_my" selectedImageName:@"home_my_pre" target:self action:@selector(rightButtonPressed:)];

  
    self.contentList = [NSMutableArray arrayWithArray:[UserSingleton shareInstance].userModel.stations];
    
    self.navigationItem.title = @"小叶WIFI管理";
    [self.view addSubview:self.headerView];
    
    
    __weak __typeof(self) weakSelf = self;
    [self.headerView setEditButtonClick:^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf gotoSettingWIFIViewController];
    }];
    
    [self.headerView setRefreshButtonClick:^{
        STRONGSELF
        [strongSelf refresh];
    }];
    
    self.tableView.separatorColor = SeparatorLineColor;
    [self.tableView remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.headerView.bottom);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    self.tableView.tableFooterView = [UIView new];
    
//    [self addLeftBarButtonWithNormalImageName:@"home_location" selectedImageName:@"home_location_pre" target:self action:@selector(leftButtonPressed:)];

    
    [self.tableView registerClass:[WIFIManagerTableViewCell class] forCellReuseIdentifier:@"WIFIManagerTableViewCell"];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(findNewWIFINotification:) name:TK_FindNewWIFINotification object:nil];
    
    [self refresh];
    
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    self.headerView.wifiModel = wifi;
    if ([wifi.status isEqualToString:@"online"]) {
        [self startUpdatingRate];
    } else {
        [self stopUpdatingRate];
        [self showOffLineView];
    }

    RateModel *rate = [UserSingleton shareInstance].userModel.rate;
    [self updateRate:rate];

}


- (void)findNewWIFINotification:(NSNotification *)notify
{
    BOOL hasNewWIFI = [[notify object] boolValue];
    if (hasNewWIFI) {
        [self addLeftBarButtonWithNormalImageName:@"home_location" selectedImageName:@"home_location_pre" target:self action:@selector(leftButtonPressed:)];
    }
    self.navigationItem.leftBarButtonItem.customView.hidden = !hasNewWIFI;
 }


- (void)leftButtonPressed:(id)sender
{
    DiscoverNewWIFIController *discoverNewWIFI = [[DiscoverNewWIFIController alloc] init];
    discoverNewWIFI.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:discoverNewWIFI animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:TK_FindNewWIFINotification object:nil];
    [self stopUpdatingRate];
}



- (void)showOffLineView
{
    WEAKSELF
    [self showNetworkExceptionWithView:self.view andTitle:@"连不上网络了!" andButtonTitle:@"点击重试" andBtnBlock:^{
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf loginRequest];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




#pragma mark -
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return 1;
}// Default is 1 if not implemented

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.contentList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WIFIManagerTableViewCell *cell = (WIFIManagerTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"WIFIManagerTableViewCell" forIndexPath:indexPath];
    cell.stationModel = self.contentList[indexPath.row];
    return cell;
}

#pragma mark -
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    WIFIDeviceSettingViewController *device = [[WIFIDeviceSettingViewController alloc] init];
    device.hidesBottomBarWhenPushed = YES;
    device.selectedIndex  = indexPath.row;
    [self.navigationController pushViewController:device animated:YES];
    
}


// 设置分隔线 iOS8 下才起作用
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}


#pragma mark -
#pragma mark   IBActions
- (void)gotoSettingWIFIViewController
{
    SettingSSIDAndPasswordViewController *modifyVC = [[SettingSSIDAndPasswordViewController alloc] init];
    modifyVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:modifyVC animated:YES];
}




- (void)refresh
{
    self.activity = [self startActivityWithTitle:@"正在刷新..."];
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    UserModel *user = [[UserSingleton shareInstance].userModel.user objectAtIndex:0];
    if (!wifi)
    {
        return;
    }

    WEAKSELF
    [self.wifiHelper refreshDataWithDeviceID:wifi.device_id userName:user.userName success:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (responseObject)
        {
            [strongSelf stopActivityWithActivity:strongSelf.activity title:@""];
            [strongSelf refreshDataWithResponse:responseObject];
        }
        else{
            [strongSelf stopActivityWithActivity:strongSelf.activity title:@"刷新失败!"];
            [strongSelf showOffLineView];

        }

    } failure:^(NSError *error) {
        NSString *failedReason = [error localizedDescription];
        [self stopActivityWithActivity:self.activity title:failedReason];
        [self showOffLineView];
    }];
}


- (void)refreshDataWithResponse:(NSDictionary *)dict
{
    if (dict)
    {
        LoginResponseModel *responseModel = [LoginResponseModel objectWithKeyValues:dict];
        self.headerView.wifiModel = responseModel.wifi;
        self.headerView.rateModel = responseModel.rate;
        
        
        [UserSingleton shareInstance].userModel.bindDevice = responseModel.bindDevice;
        [UserSingleton shareInstance].userModel.wifi = responseModel.wifi;
        [UserSingleton shareInstance].userModel.rate = responseModel.rate;
        
        NSArray *array = [responseModel.stations sortedArrayUsingComparator:^NSComparisonResult(StationModel *  _Nonnull obj1, StationModel*  _Nonnull obj2) {
            NSNumber *number1 = @(obj1.master);
            NSNumber *number2 = @(obj2.master);
            return [number2 compare:number1];
        }];
        [UserSingleton shareInstance].userModel.stations = array;
        [[UserSingleton shareInstance] saveData];

        
        self.contentList = [NSMutableArray arrayWithArray:array];
        [self.tableView reloadData];

    }

}



- (void)rightButtonPressed:(UIButton *)sender
{
    [self pushViewControllerWithClassName:NSStringFromClass([MyViewController class])];
}




- (void)loginRequest
{
    UserModel *user = [UserSingleton shareInstance].userModel.user[0];
    NSString *phone = user.userName;
    NSString *password = [UserSingleton shareInstance].password;
    
    
    self.activity = [self startActivityWithTitle:@"正在重试,请稍候..."];
    WEAKSELF
    [self.userHelper loginWithPhone:phone password:password success:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        if (succ) {
            [strongSelf stopActivityWithActivity:strongSelf.activity title:nil];
            LoginResponseModel *model = (LoginResponseModel *)responseObject;
            UserSingleton *singleton = [UserSingleton shareInstance];
            singleton.userModel = model;
            [singleton saveData];
            if ([model.wifi.status isEqualToString:@"offline"]) {
                [strongSelf showOffLineView];
            }
        }
        else{
            [strongSelf stopActivityWithActivity:strongSelf.activity title:nil];
            [strongSelf showOffLineView];
        }
    } failure:^(NSError *error) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        [strongSelf stopActivityWithActivity:strongSelf.activity title:@""];
        [strongSelf showOffLineView];
    }];
}



#pragma mark - rate

- (void)startUpdatingRate {
    [self stopUpdatingRate];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:3
                                              target:self
                                            selector:@selector(doGetRate)
                                            userInfo:nil
                                             repeats:YES];
}

- (void)stopUpdatingRate {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void)doGetRate {
    WIFIModel *wifi = [UserSingleton shareInstance].userModel.wifi;
    WEAKSELF
    [self.wifiHelper getUpLoadAnDownLoadSpeedWithDeviceID:wifi.device_id success:^(BOOL succ, id responseObject, NSString *msg) {
        STRONGSELF
        NSString *status = responseObject[@"status"];
        if ([status isEqualToString:@"online"])
        {
            RateModel *rate = [RateModel objectWithKeyValues:responseObject[@"rate"]];
            [strongSelf updateRate:rate];
        }
    } failure:^(NSError *error) {
        NSString *failedReason = [error localizedDescription];
        [self stopActivityWithActivity:self.activity title:failedReason];
        [self showOffLineView];
    }];
}



- (void)updateRate:(RateModel *)rateModel {
    if (rateModel) {
        self.headerView.rateModel = rateModel;
    }
}



#pragma mark -
#pragma mark   setters and getters
- (WIFIManagerHeaderView *)headerView
{
    if (_headerView == nil)
    {
        _headerView = [[WIFIManagerHeaderView alloc]initWithFrame:Rect(0, 0, ScreenWidth, 110)];
    }
    return _headerView;
}
@end
